package org.example.forum.controller;


import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.example.forum.common.AppResult;
import org.example.forum.common.ResultCode;
import org.example.forum.config.AppConfig;
import org.example.forum.exception.ApplicationException;
import org.example.forum.model.Article;
import org.example.forum.model.Board;
import org.example.forum.model.User;
import org.example.forum.services.IArticleService;
import org.example.forum.services.IBoardService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

@Api(tags = "文章接口")
@Slf4j
@RestController
@RequestMapping("/article")
public class ArticleController {

    @Autowired
    IArticleService articleService;

    @Autowired
    IBoardService boardService;

    @ApiOperation("发布新帖")
    @PostMapping("/create")
    public AppResult create (HttpServletRequest request,
                             @ApiParam("版块Id") @RequestParam("boardId") @NonNull Long boardId,
                             @ApiParam("文章标题") @RequestParam("title") @NonNull String title,
                             @ApiParam("文章内容") @RequestParam("content") @NonNull String content){
        //校验用户是否被禁言
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if(user.getState() == 1) {
            //用户被禁言
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_BANNED));
        }
        //校验板块信息
        Board board = boardService.selectById(boardId);
        if (board == null|| board.getDeleteState() == 1|| board.getState() == 1) {
            //打印日志
            log.warn(ResultCode.FAILED_BOARD_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_BOARD_NOT_EXISTS));
        }
        //构造文章信息
        Article article = new Article();
        article.setBoardId(boardId);
        article.setContent(content);
        article.setTitle(title);
        article.setUserId(user.getId());
        //调用service
        articleService.create(article);
        return AppResult.success();
    }

    @ApiOperation("获取帖子列表")
    @GetMapping("/getAllByBoardId")
    public AppResult<List<Article>> getAllByBoardId (
            @ApiParam("版块Id") @RequestParam(value = "boardId", required = false) Long boardId) {
        List<Article> articleList = null;
        if(boardId == null) {
            //如果参数为空则查找全部的记录
            articleList = articleService.selectAll();
        }else {
            //如果参数不为空则根据板块id查找记录
            articleList = articleService.selectAllByBoardId(boardId);
        }
        if(articleList == null) {
            // 如果结合集为空，那么创建上个空集合
            articleList = new ArrayList<>();
        }
        return AppResult.success(articleList);
    }

    @ApiOperation("根据帖子Id获取详情")
    @GetMapping("/details")
    public AppResult<Article> getDetails (HttpServletRequest request,
                                          @ApiParam("帖子Id") @RequestParam("id") @NonNull Long id) {
        // 从session中获取当前登录的用户
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);

        // 调用Service，获取帖子详情
        Article article = articleService.selectDetailById(id);
        // 判断结果是否为空
        if (article == null) {
            // 返回错误信息
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        // 判断当前用户是否为作者
        if (user.getId() == article.getUserId()) {
            // 标识为作者
            article.setOwn(true);
        }
        // 返回结果
        return AppResult.success(article);
    }

    @ApiOperation("修改帖子")
    @RequestMapping("/modify")
    public AppResult modify (HttpServletRequest request,
                             @ApiParam("帖子id")@RequestParam("id")@NonNull Long id,
                             @ApiParam("帖子标题")@RequestParam("title")@NonNull String title,
                             @ApiParam("帖子正文")@RequestParam("content")@NonNull String content) {
        //获取当前登录用户
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        //校验用户状态
        if(user.getState() == 1) {
            //返回错误结果
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        //查询帖子详情
        Article article = articleService.selectById(id);
        //校验帖子
        if(article == null) {
            //返回错误结果
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        //判断用户是否是作者
        if(article.getUserId() != user.getId()) {
            //返回错误结果
            return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
        }
        //判断帖子状态
        if(article.getState() == 1 || article.getDeleteState() == 1) {
            //返回错误结果
            return AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED);
        }
        articleService.modify(id, title, content);
        //打印日志
        log.info("更新成功，userId:{},articleId:{}",user.getId(),id);
        //返回结果
        return AppResult.success();
    }

    @ApiOperation("点赞")
    @PostMapping("/thumbsUp")
    public AppResult thumbsUp (HttpServletRequest request,
                               @ApiParam("帖子Id") @RequestParam("id") @NonNull Long id) {
        //获取当前登录用户
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        //校验用户状态
        if(user.getState() == 1) {
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        //调用service
        articleService.thumbsUpById(id);
        //返回结果
        return AppResult.success();
    }

    @ApiOperation("删除帖子")
    @PostMapping("/delete")
    public AppResult deleteById (HttpServletRequest request,
                                 @ApiParam("帖子Id") @RequestParam("id") @NonNull Long id) {
        //获取当前登录用户
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        //校验用户状态
        if(user.getState() == 1) {
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        //查询帖子详情
        Article article = articleService.selectById(id);
        //校验帖子
        if(article == null || article.getDeleteState() == 1) {
            //返回错误结果
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        //判断用户是否是作者
        if(article.getUserId() != user.getId()) {
            //返回错误结果
            return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
        }
        //调用service
        articleService.deleteById(id);
        //打印日志
        log.info("删除成功，删除帖子id:{}",id);
        //返回结果
        return AppResult.success();

    }

    @ApiOperation("获取用户的帖子列表")
    @RequestMapping("/getAllByUserId")
    public AppResult<List<Article>> getAllByUserId (HttpServletRequest request ,
                                     @ApiParam("用户id")
                                     @RequestParam(value = "userId",required = false) Long userId) {
       if (userId == null) {
           HttpSession session = request.getSession(false);
           User user = (User) session.getAttribute(AppConfig.USER_SESSION);
           userId = user.getId();
       }
       //调用service
        List<Article>  articles = articleService.selectByUserId(userId);
       //返回结果
        return AppResult.success(articles);
    }
}
